import * as step from '@flow-step/step-toolkit'
import * as path from 'path'
import * as fs from 'fs'
import { simpleGit, SimpleGit } from 'simple-git';
import {SetSSHPrivateKey} from "./sshKey"
import process from 'process'
import {masking, replaceEnvVar} from './util'
import {replace} from 'sinon'

export async function checkBranchBehind() {
    let projectDir = process.env.PROJECT_DIR as string;
    let repoDirName = path.basename(projectDir);  //the repo we work on
    SetSSHPrivateKey(repoDirName);

    process.env.GIT_SSL_NO_VERIFY = '1';
    const git: SimpleGit = simpleGit();
    git.env(process.env);
    await git.cwd(process.env.PROJECT_DIR as string);

    const targetBranch = replaceEnvVar(process.env.TARGET_BRANCH as string);
    const ciBranch = process.env.CI_COMMIT_REF_NAME as string;

    step.info(`Checking if there are commits on the ${targetBranch} that do not exist on the ${ciBranch} branch.`)
    step.info(`git fetch && git diff HEAD...origin/${targetBranch}`);

    try{
        await git.fetch();
    }catch (error:any){
        step.error(`git fetch failed: ${masking(error.message)}`);
    }

    let checkOutput = await git.diff([`HEAD...origin/${targetBranch}`])

    if (checkOutput.length == 0) {
        step.info(`branch '${ciBranch}' is up to date with or ahead of '${targetBranch}', continue running.`)
    }else{
        step.error(`'${targetBranch}' has commits that '${ciBranch}' has not. Please merge '${targetBranch}' into '${ciBranch}' locally, push and rerun the pipeline.`);
        step.info(`commit ID of branch '${ciBranch}' is ${process.env.CI_COMMIT_SHA}`);
        process.exit(1);
    }
}